package com.yanfan.mq.service;

import cn.hutool.core.collection.CollUtil;
import com.yanfan.common.core.mq.DeviceReport;
import com.yanfan.common.core.mq.DeviceReportBo;
import com.yanfan.common.core.mq.message.DeviceData;
import com.yanfan.common.enums.TopicType;
import com.yanfan.common.exception.ServiceException;
import com.yanfan.iot.model.DeviceStatusVO;
import com.yanfan.iot.service.IDeviceService;
import com.yanfan.iot.service.IProductService;
import com.yanfan.protocol.base.protocol.IProtocol;
import com.yanfan.protocol.service.IProtocolManagerService;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@Component
public class IMqttMessageSubscribeAware implements ApplicationContextAware {

    private List<IMqttMessageService> implServiceList;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProtocolManagerService protocolManagerService;
    @Autowired
    private IDeviceService deviceService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 通过上下文，根据接口类型返回相应的所有实现类bean
        Map<String, IMqttMessageService> implServiceMap = applicationContext.getBeansOfType(IMqttMessageService.class);
        implServiceList = new ArrayList<>(implServiceMap.values());
    }

    /**
     * 设备上报的数据接口
     * */
    public void publishMessage(DeviceReport message, String topicName) {
        if (CollUtil.isEmpty(implServiceList)) {
            return;
        }

        for (IMqttMessageService messageService : implServiceList) {
            try {
                messageService.message(message, topicName);
            } catch (Exception e) {
                log.error("内部消息处理异常，msg:{}", e.getMessage(), e);
            }
        }
    }

    /**
     * 平台下发到设备的接口
     * */
    public void subscribeMessage(DeviceReportBo reportBo) {
        if (CollUtil.isEmpty(implServiceList)) {
            return;
        }
        if (reportBo.getTopicName().endsWith(TopicType.MESSAGE_POST.getTopicSuffix())) {
            return;
        }

        DeviceReport deviceReport = parseReportMsg(reportBo);
        for (IMqttMessageService messageService : implServiceList) {
            try {
                messageService.subscribe(deviceReport, reportBo.getTopicName(), reportBo);
            } catch (Exception e) {
                log.error("内部消息处理异常，msg:{}", e.getMessage(), e);
            }
        }
    }


    /**
     * 构建消息
     *
     * @param bo
     */
    private DeviceStatusVO buildReport(DeviceReportBo bo) {
        DeviceStatusVO deviceStatusVO = deviceService.selectDeviceStatusAndTransportStatus(bo.getSerialNumber());
        Optional.ofNullable(deviceStatusVO).orElseThrow(() -> new ServiceException("设备不存在"));
        //产品id
        bo.setProductId(deviceStatusVO.getProductId());
        return deviceStatusVO;
    }

    private IProtocol selectedProtocol(Long productId) {
        //查询产品获取协议编号
        String code = productService.getProtocolByProductId(productId);
        return protocolManagerService.getProtocolByProtocolCode(code);
    }


    private DeviceReport parseReportMsg(DeviceReportBo bo) {
        String serialNumber = bo.getSerialNumber();
        //构建消息
        DeviceStatusVO deviceStatusVO = buildReport(bo);
        Long productId = bo.getProductId();
        /*获取协议处理器*/
        IProtocol protocol = selectedProtocol(productId);
        DeviceData data = DeviceData.builder().serialNumber(serialNumber).topicName(bo.getTopicName()).productId(deviceStatusVO.getProductId()).data(
                bo.getData()).buf(Unpooled.wrappedBuffer(bo.getData())).build();
        /*根据协议解析后的数据*/
        return protocol.decode(data, serialNumber);
    }
}
